﻿using AutoMapper;
using Harmontronics.DataAccess.IOperate.Business;
using Harmontronics.DataAccess.Operate.Business;
using Harmontronics.IService;
using Harmontronics.IService.Business;
using Harmontronics.Model.Dto;
using Harmontronics.Model.Dto.Model;
using Harmontronics.Model.Entitys;
using Harmontronics.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Harmontronics.Service
{
    public class PartDetailsService : IPartDetailsService
    {
        private readonly IMapper _mapper;
        private readonly IUnitOfWork _unitOfWork;
        private IPartOperate _partOperate;
        private IRecipeOperate _recipeOperate;
        private IUserRecipeOperate _userRecipeOperate;
        private IMaterialOperate _materialOperate;
        public PartDetailsService(IUnitOfWork unitOfWork, IMapper mapper,
            IPartOperate partOperate, IRecipeOperate recipeOperate, IUserRecipeOperate userRecipeOperate, IMaterialOperate materialOperate)
        {
            _mapper = mapper;
            _unitOfWork = unitOfWork;
            _partOperate = partOperate;
            _recipeOperate = recipeOperate;
            _userRecipeOperate = userRecipeOperate;
            _materialOperate = materialOperate;
        }

        public List<PartDetailModel> GetPartDetails()
        {
            List<PartDetailModel> models = new List<PartDetailModel>();
            List<Part> parts = _partOperate.GetAllPartList();
            List<string> RecipeIds = parts.Select(x => x.RecipeId).Distinct().ToList();
            List<UserRecipe> userRecipes = _userRecipeOperate.GetUserRecipeByRecipeIdList(RecipeIds);
            List<Recipe> recipes = _recipeOperate.GetRecipeByIdList(RecipeIds);

            foreach (UserRecipe userRecipe in userRecipes)
            {
                Part part = parts.SingleOrDefault(x => x.RecipeId == userRecipe.RecipeId);
                Recipe recipe = recipes.SingleOrDefault(x => x.RecipeId == userRecipe.RecipeId);
                PartDetailModel model = new PartDetailModel();
                model.RecipeId = userRecipe.RecipeId;
                model.ParameterValue = userRecipe.ParameterValue;
                model.ParameterId = userRecipe.ParameterId;
                model.PartId = (part == null) ? string.Empty : part.PartId;
                model.RecipeTypeId = (recipe == null) ? string.Empty : recipe.RecipeTypeId;
                models.Add(model);
            }
            return models;
        }
    }
}
